package com.lgh.ibs.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.eclipse.swt.widgets.ProgressBar;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.io.svn.SVNRepositoryFactoryImpl;
import org.tmatesoft.svn.core.internal.wc.DefaultSVNOptions;
import org.tmatesoft.svn.core.wc.ISVNOptions;
import org.tmatesoft.svn.core.wc.SVNClientManager;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNUpdateClient;
import org.tmatesoft.svn.core.wc.SVNWCUtil;

import com.lgh.ibs.entity.SVN;
import com.lgh.ibs.factory.IbsPlusParamFactory;
import com.lgh.ibs.log.IbsLogger;

/**
 * SVN操作工具
 * 
 * @author ghli
 *
 */
public class SVNOptionUtil {

	// 声明SVN客户端管理类
	private static SVNClientManager ourClientManager;

	/**
	 * @Title: checkOut
	 * @Description:SVN项目检出
	 * @param svnUrlList
	 * @param workSpacePath
	 * @param progressBar 
	 * @throws SVNException
	 * @throws @author
	 *             guohao.li
	 * @dateTime 2016年12月21日 上午11:24:23
	 */
	public static void checkOut(List<String> svnUrlList, String workSpacePath, ProgressBar progressBar) throws Exception {
		// 初始化支持svn://协议的库。 必须先执行此操作。
		SVNRepositoryFactoryImpl.setup();
		// 相关变量赋值
		SVNURL repositoryURL = null;
		ISVNOptions options = SVNWCUtil.createDefaultOptions(true);
		
		SVN svnInstance = IbsPlusParamFactory.getSVNInstance();
		// 实例化客户端管理类
		ourClientManager = SVNClientManager.newInstance((DefaultSVNOptions) options, 
				svnInstance.getUserName(), svnInstance.getPwd());
		for (int i = 0; i < svnUrlList.size(); i++) {
			String svnUrl = svnUrlList.get(i);
			progressBar.setSelection(i);
			svnUrl = svnUrl.replace("\\", "/").replace("\\n", "").replace("\r\n", "");
			try {
				// repositoryURL = SVNURL.parseURIEncoded("svn://" + svnUrl);
				// String svnUrl =
				// "https://svn.99wuxian.com:8443/svn/ibsModule/codeResource/deploy/entity-base/branches/v1.2.0";
				repositoryURL = SVNURL.parseURIEncoded(svnUrl);
			} catch (SVNException e) {
				IbsLogger.INFO("svn 无法连接");
				throw e;
			}
			// 要把版本库的内容check out到的目录
			String workPath = "";
			if(workSpacePath.endsWith("\\") || workSpacePath.endsWith("/")){
				workPath = workSpacePath + getSvnProjectName(svnUrl);
			}else{
				workPath = workSpacePath + "/" + getSvnProjectName(svnUrl);
			}
			File wcDir = new File(workPath);
			// 通过客户端管理类获得updateClient类的实例。
			SVNUpdateClient updateClient = ourClientManager.getUpdateClient();
			updateClient.setIgnoreExternals(false);
			// 执行check out 操作，返回工作副本的版本号。
			long workingVersion = updateClient.doCheckout(repositoryURL, wcDir, SVNRevision.HEAD, SVNRevision.HEAD,
					SVNDepth.INFINITY, false);
			IbsLogger.INFO("把版本：" + workingVersion + " check out 到目录：" + wcDir + "中。");
			Thread.sleep(1000);
		}
		ourClientManager.dispose();
	}

	/**
	 * @Title: getSvnProjectName 
	 * @Description: 根据svn路径取出工程名称 
	 * @param svnUrl
	 * @return
	 * @throws Exception 
	 * @throws 
	 * @author guohao.li
	 * @dateTime 2016年12月21日 下午2:15:19
	 */
	private static String getSvnProjectName(String svnUrl) throws Exception {
		String projectName = "";
//		String regex = "^http{1}.+/svn/ibsModule/codeResource/(deploy/{1}.+/branches{1}).+";
		SVN svn = IbsPlusParamFactory.getSVNInstance();
		//分支
		String branchesRegex = svn.getSvnPathVerifyRegex();
		//主分支
		if(svnUrl.contains("trunk")){
			branchesRegex = branchesRegex.replace("branches", "trunk");
		}
		Pattern p = Pattern.compile(branchesRegex);
		
		Matcher m = p.matcher(svnUrl);
		boolean result = m.matches();
		System.out.println(result);
		if(result && m.groupCount()==1){
			//这里再次匹配一次是因为上一次matches()后匹配器的内容已改变,否则将取不到group里的值 
			 m = p.matcher(svnUrl);
			while (m.find()) {
				if(svnUrl.contains("trunk")){
					projectName = m.group(1).replace("deploy/", "").replace("/trunk", "");
				}else{
					projectName = m.group(1).replace("deploy/", "").replace("/branches", "");
				}
			}
		}else{
			throw new RuntimeException("SVN路径不合法！请检查正则配置！"+ svnUrl);
		}
		return projectName;
	}


	public static void main(String... args) throws Exception {
		List<String> svnUrlList = new ArrayList<String>();
		svnUrlList.add("https://xxxsxxxxx/svn/ibsModule/codeResource/deploy/root/branches/v3.11.0");
		
		String workSpacePath = "E:\\svntest\\";
		checkOut(svnUrlList, workSpacePath, null);

	}
}